<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单数据调试工具</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 800px; margin: 40px auto; padding: 0 20px; }
        h1 { color: #333; }
        .section { margin: 20px 0; padding: 20px; background: #f5f5f5; border-radius: 8px; }
        button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; margin-right: 10px; }
        button:hover { background: #1565c0; }
        pre { background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 4px; overflow-x: auto; max-height: 400px; }
        .success { color: #4caf50; }
        .error { color: #f44336; }
        .log-container { margin-top: 20px; }
        .log-tabs { display: flex; margin-bottom: 10px; }
        .log-tab { padding: 8px 16px; background: #e0e0e0; border: none; cursor: pointer; margin-right: 5px; border-radius: 4px 4px 0 0; }
        .log-tab.active { background: #1976d2; color: white; }
        .log-content { display: none; }
        .log-content.active { display: block; }
    </style>
</head>
<body>
    <h1>订单数据调试工具</h1>
    
    <div class="section">
        <h2>1. 设置Token</h2>
        <button id="setTokenBtn">设置模拟Token</button>
        <div id="tokenResult" class="success"></div>
    </div>
    
    <div class="section">
        <h2>2. 测试订单数据处理流程</h2>
        <button id="testFullFlowBtn">完整测试流程</button>
        <button id="testFilterBtn">仅测试过滤逻辑</button>
    </div>
    
    <div class="log-container">
        <div class="log-tabs">
            <button class="log-tab active" onclick="showLog('api')">API响应</button>
            <button class="log-tab" onclick="showLog('transformed')">转换后数据</button>
            <button class="log-tab" onclick="showLog('filtered')">过滤后数据</button>
            <button class="log-tab" onclick="showLog('status')">状态映射</button>
        </div>
        
        <div id="apiLog" class="log-content active">
            <pre id="apiResponseLog">点击按钮开始测试...</pre>
        </div>
        
        <div id="transformedLog" class="log-content">
            <pre id="transformedDataLog">点击按钮开始测试...</pre>
        </div>
        
        <div id="filteredLog" class="log-content">
            <pre id="filteredDataLog">点击按钮开始测试...</pre>
        </div>
        
        <div id="statusLog" class="log-content">
            <pre id="statusMappingLog">点击按钮开始测试...</pre>
        </div>
    </div>
    
    <script>
        // 状态映射表
        const statusMap = {
            'pending': '待付款',
            'paid': '待发货',
            'shipped': '待收货',
            'completed': '已完成',
            'cancelled': '已取消'
        };
        
        // 状态数字转字符串
        function getStatusString(statusNumber) {
            const statusMap = {
                1: 'pending',
                2: 'paid',
                3: 'shipped',
                4: 'completed',
                5: 'cancelled'
            };
            return statusMap[statusNumber] || 'unknown';
        }
        
        // 格式化日期时间
        function formatDate(dateString) {
            if (!dateString) return '无';
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return '无';
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 格式化订单商品数据
        function formatOrderItems(order) {
            if (!order) return [];
            
            // 如果已经有items数组，直接返回
            if (order.items && Array.isArray(order.items)) {
                return order.items;
            }
            
            // 否则，根据firstProductName和productCount创建模拟items数组
            const items = [];
            if (order.firstProductName && order.productCount > 0) {
                // 至少创建一个商品项
                items.push({
                    id: `item_${order.id}_1`,
                    productName: order.firstProductName,
                    price: order.totalAmount / order.productCount, // 平均价格
                    quantity: 1,
                    productImage: `https://picsum.photos/id/${(parseInt(order.id) || 26) % 100}/80/80`
                });
                
                // 如果商品数量大于1，创建更多商品项
                for (let i = 2; i <= order.productCount; i++) {
                    items.push({
                        id: `item_${order.id}_${i}`,
                        productName: `${order.firstProductName} 等`,
                        price: order.totalAmount / order.productCount, // 平均价格
                        quantity: 1,
                        productImage: `https://picsum.photos/id/${(parseInt(order.id) + i) % 100}/80/80`
                    });
                }
            }
            
            return items;
        }
        
        // 过滤订单逻辑
        function filterOrders(orders, activeTab) {
            console.log('===== 过滤订单开始 =====');
            console.log('当前激活标签:', activeTab);
            console.log('订单数据数量:', orders.length);
            
            // 记录订单状态分布统计
            const statusStats = orders.reduce((acc, order) => {
                acc[order.status] = (acc[order.status] || 0) + 1;
                return acc;
            }, {});
            console.log('订单状态分布:', statusStats);
            
            let result = [];
            
            if (activeTab === 'all') {
                console.log('选择全部订单，返回所有', orders.length, '条数据');
                result = orders;
            } else {
                // 尝试使用status字段过滤
                console.log('使用标签', activeTab, '进行过滤');
                let filtered = orders.filter(order => order.status === activeTab);
                console.log('使用status字段过滤后数量:', filtered.length);
                
                // 如果过滤后没有数据，返回所有订单
                if (filtered.length === 0 && orders.length > 0) {
                    console.warn('状态过滤失败，返回所有订单数据');
                    result = orders;
                } else {
                    result = filtered;
                }
            }
            
            console.log('最终返回的订单数量:', result.length);
            console.log('===== 过滤订单结束 =====');
            return result;
        }
        
        // 设置Token
        document.getElementById('setTokenBtn').addEventListener('click', function() {
            try {
                localStorage.setItem('token', 'mock-token-for-testing');
                document.getElementById('tokenResult').textContent = '✅ Token已成功设置！值为：mock-token-for-testing';
                console.log('Token已设置:', localStorage.getItem('token'));
            } catch (e) {
                document.getElementById('tokenResult').textContent = '❌ 设置Token失败：' + e.message;
                document.getElementById('tokenResult').className = 'error';
            }
        });
        
        // 完整测试流程
        document.getElementById('testFullFlowBtn').addEventListener('click', async function() {
            document.getElementById('apiResponseLog').textContent = '正在请求订单数据...';
            document.getElementById('transformedDataLog').textContent = '正在处理数据...';
            document.getElementById('filteredDataLog').textContent = '等待数据处理完成...';
            document.getElementById('statusMappingLog').textContent = '等待数据处理完成...';
            
            try {
                // 构建查询参数
                const queryParams = new URLSearchParams({
                    pageNum: 1,
                    pageSize: 10,
                    userId: '1'
                });
                
                // 构建请求URL
                const url = `/order/list?${queryParams.toString()}`;
                console.log('请求URL:', url);
                
                // 获取token
                const token = localStorage.getItem('token');
                console.log('使用Token:', token);
                
                // 发送请求
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });
                
                console.log('响应状态码:', response.status);
                
                // 解析响应数据
                const data = await response.json();
                console.log('API响应数据:', data);
                document.getElementById('apiResponseLog').textContent = JSON.stringify(data, null, 2);
                
                // 检查数据结构
                if (data?.code === 200 && data.data?.records && Array.isArray(data.data.records)) {
                    console.log('原始订单记录数量:', data.data.records.length);
                    
                    // 转换后端返回的数据结构
                    const transformedOrders = data.data.records.map(order => {
                        const orderId = order.id || order.orderNo || `order_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                        const orderStatus = order.orderStatus || order.status || 1;
                        const statusStr = getStatusString(orderStatus);
                        
                        console.log('转换订单数据:', { 
                            originalStatus: orderStatus, 
                            convertedStatus: statusStr,
                            orderNo: order.orderNo 
                        });
                        
                        return {
                            id: orderId,
                            orderNo: order.orderNo || `NO_${orderId}`,
                            status: statusStr,
                            statusText: order.orderStatusDesc || statusMap[statusStr] || '未知状态',
                            totalAmount: order.totalAmount || order.amount || 0,
                            createTime: formatDate(order.createTime || order.createdAt),
                            items: formatOrderItems(order)
                        };
                    });
                    
                    console.log('转换后订单数据:', transformedOrders);
                    document.getElementById('transformedDataLog').textContent = JSON.stringify(transformedOrders, null, 2);
                    
                    // 记录状态分布
                    const statusStats = transformedOrders.reduce((acc, order) => {
                        acc[order.status] = (acc[order.status] || 0) + 1;
                        return acc;
                    }, {});
                    
                    const statusMappingInfo = {
                        statusStats: statusStats,
                        statusMap: statusMap,
                        activeTabs: ['all', 'pending', 'paid', 'shipped', 'completed', 'cancelled']
                    };
                    
                    console.log('订单状态映射信息:', statusMappingInfo);
                    document.getElementById('statusMappingLog').textContent = JSON.stringify(statusMappingInfo, null, 2);
                    
                    // 测试过滤逻辑
                    const filtered = filterOrders(transformedOrders, 'all');
                    console.log('过滤后订单数据:', filtered);
                    document.getElementById('filteredDataLog').textContent = JSON.stringify(filtered, null, 2);
                    
                    // 在控制台中显示关键信息
                    console.log('===== 关键调试信息 =====');
                    console.log('原始记录数:', data.data.records.length);
                    console.log('转换后记录数:', transformedOrders.length);
                    console.log('过滤后记录数:', filtered.length);
                    console.log('状态分布:', statusStats);
                    
                } else {
                    console.error('响应数据结构不符合预期');
                    document.getElementById('apiResponseLog').textContent = '❌ 响应数据结构不符合预期\n' + JSON.stringify(data, null, 2);
                }
                
            } catch (error) {
                console.error('请求失败:', error);
                document.getElementById('apiResponseLog').textContent = '❌ 请求失败\n' + error.message;
            }
        });
        
        // 仅测试过滤逻辑
        document.getElementById('testFilterBtn').addEventListener('click', function() {
            // 使用模拟数据测试过滤逻辑
            const mockOrders = [
                {
                    id: '1',
                    orderNo: 'ORD20240101001',
                    status: 'pending',
                    statusText: '待付款',
                    totalAmount: 100.00,
                    createTime: '2024-01-01 10:00',
                    items: [{id: '1-1', productName: '商品1', price: 100.00, quantity: 1}]
                },
                {
                    id: '2',
                    orderNo: 'ORD20240101002',
                    status: 'paid',
                    statusText: '待发货',
                    totalAmount: 200.00,
                    createTime: '2024-01-01 11:00',
                    items: [{id: '2-1', productName: '商品2', price: 200.00, quantity: 1}]
                },
                {
                    id: '3',
                    orderNo: 'ORD20240101003',
                    status: 'shipped',
                    statusText: '待收货',
                    totalAmount: 300.00,
                    createTime: '2024-01-01 12:00',
                    items: [{id: '3-1', productName: '商品3', price: 300.00, quantity: 1}]
                }
            ];
            
            console.log('使用模拟数据测试过滤逻辑:', mockOrders);
            document.getElementById('transformedDataLog').textContent = JSON.stringify(mockOrders, null, 2);
            
            // 测试过滤逻辑
            const filtered = filterOrders(mockOrders, 'all');
            console.log('过滤后订单数据:', filtered);
            document.getElementById('filteredDataLog').textContent = JSON.stringify(filtered, null, 2);
            
            // 记录状态分布
            const statusStats = mockOrders.reduce((acc, order) => {
                acc[order.status] = (acc[order.status] || 0) + 1;
                return acc;
            }, {});
            
            const statusMappingInfo = {
                statusStats: statusStats,
                statusMap: statusMap,
                activeTabs: ['all', 'pending', 'paid', 'shipped', 'completed', 'cancelled']
            };
            
            document.getElementById('statusMappingLog').textContent = JSON.stringify(statusMappingInfo, null, 2);
            document.getElementById('apiResponseLog').textContent = '使用模拟数据进行测试，未调用实际API';
        });
        
        // 显示指定的日志标签
        function showLog(tabName) {
            // 隐藏所有日志内容
            document.querySelectorAll('.log-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签的激活状态
            document.querySelectorAll('.log-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的日志内容和标签
            document.getElementById(`${tabName}Log`).classList.add('active');
            document.querySelector(`.log-tab[onclick="showLog('${tabName}')"]`).classList.add('active');
        }
        
        // 页面加载时检查token
        window.onload = function() {
            const token = localStorage.getItem('token');
            if (token) {
                document.getElementById('tokenResult').textContent = `当前已有Token: ${token}`;
            } else {
                document.getElementById('tokenResult').textContent = '尚未设置Token，请点击按钮设置';
                document.getElementById('tokenResult').className = 'error';
            }
        };
    </script>
</body>
</html>